package com.cndongtai.interceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.cndongtai.constant.SystemConstant;
import com.cndongtai.constant.UserConstant;
import com.cndongtai.po.User;

public class SessionInterceptor extends HandlerInterceptorAdapter{

	private final Logger logger = Logger.getLogger(SessionInterceptor.class);
	
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		
		checkLanguage(request);
		
		String uri = request.getRequestURI();
		if(uri.contains("/login.do") || uri.contains("/loginpage.do") || uri.contains("/torchn/") || uri.contains("/torchnapp/")
				|| uri.contains("/addLightNew.do") || uri.contains("/updateDtuLocation.do")
				|| uri.contains("/downloadFirmware.do") || uri.contains("/torchnpage.do")) {
			return true;
		}
		
		User user = (User) request.getSession().getAttribute(UserConstant.SESSION_USER);
		if(user==null) {
			String requestType = request.getHeader("X-Requested-With");
			if(requestType != null && requestType.equals("XMLHttpRequest")){
    			PrintWriter out = response.getWriter();
    			out.print("noSession");
    		}else{
				StringBuffer script = new StringBuffer("<script type=\"text/javascript\">");
				script.append(" try{if(window.dialogArguments) {")
					  .append("window.close();")
					  .append(" window.dialogArguments.parent.location.href='")
					  .append(request.getContextPath())
					  .append("/page/login.jsp';} ")
					  .append(" else if(window.opener) {window.close(); window.opener.location.href='")
					  .append(request.getContextPath()).append("/page/login.jsp';} else ")
					  .append("parent.window.location.href='")
					  .append(request.getContextPath())
					  .append("/page/login.jsp';").append("} catch(err){}")
					  .append("</script>");
				
				response.setContentType("text/html; charset=utf-8");
				writeResponse(response, script.toString());
			}
			
			return false;
		}
		
		return super.preHandle(request, response, handler);
	}
	
	private void checkLanguage(HttpServletRequest request) {
		String language = (String) request.getSession().getAttribute(SystemConstant.LANGUAGE);
		if(language==null || "".equals(language)) {
			request.getSession().setAttribute(SystemConstant.LANGUAGE, Locale.getDefault().getLanguage());
		}
		
		if("en".equals(request.getParameter("language"))) {
			request.getSession().setAttribute(SystemConstant.LANGUAGE, "en");
		}else if("zh".equals(request.getParameter("language"))) {
			request.getSession().setAttribute(SystemConstant.LANGUAGE, "zh");
		}
	}
	
	private  void writeResponse(HttpServletResponse httpResponse,
			String pageCode) {
		PrintWriter out = null;
		try {
			httpResponse.setContentType("text/html");
			httpResponse.setCharacterEncoding("utf-8");
			out = httpResponse.getWriter();

		} catch (IOException e) {
			logger.error(e.getMessage());
			return;
		}
		out.flush();
		out.write(pageCode);
		out.flush();
		out.close();
		return;
	}

}
